<template>
  <div class="users">
    <breadcrumb :breadcrumb="breadcrumb"></breadcrumb>
    <div class="content">
      <!-- 搜索及添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="query"
            class="input-with-select"
            clearable
            @clear="getusers"
          >
            <el-button @click="serach" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="addDialogFormVisible = true" type="primary">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="120px"></el-table-column>
        <el-table-column label="状态" width="100px">
          <!-- 作用域插槽  可以使用 简写#default="scope"  / v-slot="scope" -->
          <template #default="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="setstate($event,scope.row.id)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170px">
          <template #default="scope">
            <el-button @click="isShow(scope.row.id)" type="primary" icon="el-icon-edit" circle></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                @click="showSetRolesDialog(scope.row)"
                type="warning"
                icon="el-icon-setting"
                circle
              ></el-button>
            </el-tooltip>
            <el-popconfirm class="del" title="确定不是手抖了，是真的要删除吗？" @onConfirm="delUser(scope.row.id)">
              <el-button slot="reference" type="danger" icon="el-icon-delete" circle></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加用户弹出框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogFormVisible"
        :lock-scroll="false"
        @close="resetForm('addFormRef')"
      >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="addForm.password" type="password" placeholder="8-16位的密码"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="addForm.email" placeholder="xxxx@xxx.com"></el-input>
          </el-form-item>
          <el-form-item label="用户手机" prop="mobile">
            <el-input v-model="addForm.mobile" placeholder="131xxxxxxxx"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addusers">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑用户弹出框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="editDialogFormVisible"
        :lock-scroll="false"
        @close="resetForm('editFormRef')"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input :disabled="true" v-model="editForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="xxxx@xxx.com"></el-input>
          </el-form-item>
          <el-form-item label="用户手机" prop="mobile">
            <el-input v-model="editForm.mobile" placeholder="131xxxxxxxx"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUsers">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配用户角色弹出框 -->
      <el-dialog
        width="40%"
        @close="clearRoles"
        title="分配用户角色"
        :visible.sync="setRolesDialog"
        :lock-scroll="false"
      >
        <div class="roles">
          当前的用户：
          <el-input size="large" disabled v-model="userInfo.username"></el-input>
        </div>
        <div class="roles">
          当前的角色：
          <el-input size="large" disabled v-model="userInfo.role_name"></el-input>
        </div>
        <div class="roles">
          分配的角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="setRolesDialog = false">取 消</el-button>
          <el-button type="primary" @click="setRoles">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page.sync="pagenum"
          :page-sizes="[1, 5, 10]"
          :page-size.sync="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalpage"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
           
<script>
export default {
  name: "users",
  data() {
    // 自定义检验规则
    // 校验邮箱
    var validateEmail = (rule, value, callback) => {
      if (
        !/^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/.test(value.trim())
      ) {
        callback(new Error("请输入正确的邮箱格式,例:xxxx@xxx.com"));
      } else {
        callback();
      }
    };
    // 校验手机号
    var validateMobile = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value.trim())) {
        callback(new Error("手机号格式有误！"));
      } else {
        callback();
      }
    };
    return {
      breadcrumb: ["用户管理", "用户列表"],
      // 用户输入查询内容
      query: "",
      // 列表数据
      tableData: [],
      // 当前页码
      pagenum: 1,
      // 每页显示条数
      pagesize: 5,
      // 总数据条数
      totalpage: 0,
      // 添加用户弹框的显示与隐藏
      addDialogFormVisible: false,
      // 添加用户的数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加用户的数据校验规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 8, max: 16, message: "长度在 8 到 16 位", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { len: 11, message: "请输入正确的手机号码", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ]
      },
      formLabelWidth: "80px",
      // 编辑用户弹框的显示与隐藏
      editDialogFormVisible: false,
      // 编辑用户的数据
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { len: 11, message: "请输入正确的手机号码", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ]
      },
      // 分配用户角色
      setRolesDialog: false,
      // 分配角色时，用信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      //保存用户选中的角色id
      selectedRoleId: ""
    };
  },
  created() {
    this.getusers();
  },
  methods: {
    // 初始化
    getusers() {
      // 发送请求====获取用户信息
      this.$http
        .get("/users", {
          params: {
            query: this.query,
            pagenum: this.pagenum,
            pagesize: this.pagesize
          }
        })
        .then(res => {
          if (res.status == 200) {
            this.totalpage = res.data.data.total;
            this.tableData = res.data.data.users;
          }
        });
    },
    // 搜索
    serach() {
      this.getusers();
    },
    // 设置状态
    setstate($event, id) {
      this.$http.put(`users/${id}/state/${$event}`).then(res => {
        if (res.status == 200) {
          this.$message({
            message: res.data.meta.msg || "设置成功",
            type: "success",
            duration: 1000
          });
        }
      });
    },
    // 切换每页显示的数量
    handleSizeChange(val) {
      this.getusers();
    },
    // 切换页数
    handleCurrentChange(val) {
      this.getusers();
    },
    // 添加新用户
    addusers() {
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          this.$http.post("/users", this.addForm).then(res => {
            if (res.status == 200) {
              this.$message({
                message: res.data.meta.msg || "添加成功",
                type: "success",
                duration: 1000
              });
              this.addDialogFormVisible = false;
              // 重新渲染数据
              this.getusers();
            }
          });
        } else {
          return false;
        }
      });
    },
    // 重置数据
    resetForm(FormRef) {
      this.$refs[FormRef].resetFields();
    },
    // 显示编辑弹框
    async isShow(id) {
      // 让弹框显示
      this.editDialogFormVisible = true;
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status == 200) {
        this.editForm = res.data;
      }
    },
    // 编辑用户信息
    editUsers() {
      this.$refs.editFormRef.validate(valid => {
        if (valid) {
          this.$http
            .put(`/users/${this.editForm.id}`, {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            })
            .then(res => {
              if (res.status == 200) {
                this.$message({
                  message: res.data.meta.msg || "添加成功",
                  type: "success",
                  duration: 1000
                });
                this.editDialogFormVisible = false;
                // 重新渲染数据
                this.getusers();
              }
            });
        } else {
          return false;
        }
      });
    },
    // 删除用户
    delUser(id) {
      this.$http.delete(`users/${id}`).then(res => {
        if (res.status == 200) {
          this.$message({
            message: res.data.meta.msg || "删除成功",
            type: "success",
            duration: 1000
          });
          // 重新渲染数据
          this.getusers();
        }
      });
    },
    // 弹出分配角色弹框
    async showSetRolesDialog(userInfo) {
      // 1.将用户信息传入
      this.userInfo = userInfo;
      // 2.渲染新角色列表
      const { data: res } = await this.$http.get("roles");
      this.rolesList = res.data;
      // 3.显示弹框
      this.setRolesDialog = true;
    },
    // 分配角色
    async setRoles() {
      // 判断是否有选择
      if (!this.selectedRoleId)
        return this.$message.error("请选择需要分配的角色");
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      );
      // 清空
      this.clearRoles();
      this.setRolesDialog = false;
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // 重新渲染数据
      this.getusers();
    },
    clearRoles() {
      this.selectedRoleId = "";
      this.userInfo = {};
      this.rolesList = [];
    }
  }
};
</script>
<style scoped lang='less'>
.users {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .content {
    padding: 10px 20px;
    flex: 1;
    background-color: #fff;
    margin-top: 20px;
    border-radius: 8px;
    .el-row {
      .el-col {
        border-radius: 4px;
        .el-input {
          width: 100%;
        }
      }
    }
    .el-table {
      margin-top: 10px;
      .del {
        margin-left: 10px;
      }
    }
    .block {
      margin-top: 10px;
    }
    .roles {
      margin: 10px;
      .el-input {
        width: 260px;
      }
      .el-select {
        width: 260px;
      }
    }
  }
}
</style>